﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DT.Core.Models;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using StackExchange.Profiling.Internal;
using XCPFrame.Core.Enums;
using XCPFrame.Core.Plugins;
using XCPFrame.Core.ViewModels;

namespace XCPFrame.Application.Api
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [AppAuthorize, ApiDescriptionSettings("用户管理")]
    public class UserApiService : IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;
        //private readonly IWebHostEnvironment _hostingEnvironment;

        /// <summary>
        /// 用户管理API
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        /// <param name="sqlSugarRepository"></param>
        public UserApiService(IHttpContextAccessor httpContextAccessor, ISqlSugarRepository sqlSugarRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            repository = sqlSugarRepository;
            db = repository.Context;
        }

        /// <summary>
        /// 分页加载用户列表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        public PagedList<BaUser> PostUserListByPageOld(SearchByPageViewModel<BaUser> searchModel)
        {
            int totalCount = 0;

            if (searchModel.queryParams == null) { throw Oops.Oh(SystemErrorCodes.E0008); }

            string sql = "";

            List<BaUser> list;

            //注意：SugarParameter 参数名必须带@，值默认带单引号。
            sql = "select * from ba_user  where delete_flag=0 ";

            List<SugarParameter> param = new List<SugarParameter>();

            if (!searchModel.queryParams.Code.IsNullOrWhiteSpace())
            {
                sql += " and code like @code ";
                param.Add(new SugarParameter("@code", "%" + searchModel.queryParams.Code + "%"));
            }


            if (!searchModel.queryParams.Name.IsNullOrWhiteSpace())
            {
                sql += " and name like @name ";
                param.Add(new SugarParameter("@name", "%" + searchModel.queryParams.Name + "%"));
            }

            if (!searchModel.queryParams.MobilePhone.IsNullOrWhiteSpace())
            {
                sql += " and mobile_phone like @mobilephone ";
                param.Add(new SugarParameter("@mobilephone", "%" + searchModel.queryParams.MobilePhone + "%"));
            }

            if (!(searchModel.queryParams.Sex == null))
            {
                sql += " and sex = @sex";
                param.Add(new SugarParameter("@sex", searchModel.queryParams.Sex));
            }

            //配置用户角色
            db.ConfigQuery.SetTable<SysRole>(it => it.Id, it => it.Name);

            list = db.SqlQueryable<BaUser>(sql).AddParameters(param).Select((u) => new BaUser
            {
                Id = u.Id.SelectAll(),
                RoleName = u.RoleId.GetConfigValue<SysRole>()
            })
            .ToPageList(searchModel.pageIndex, searchModel.pageSize, ref totalCount);



            PagedList<BaUser> rs = new PagedList<BaUser>();

            rs.Items = list;

            rs.TotalCount = totalCount;

            rs.PageSize = searchModel.pageSize;

            return rs;
        }


        /// <summary>
        /// 分页加载用户列表
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        public PagedList<BaUser> PostUserListByPage(SearchByPageViewModel<BaUser> searchModel)
        {
            int totalCount = 0;

            if (searchModel.queryParams == null) { throw Oops.Oh(SystemErrorCodes.E0008); }


            List<BaUser> list;

            List<IConditionalModel> param = new List<IConditionalModel>();

            param.Add(
                new ConditionalModel
                {
                    FieldName = "id",
                    ConditionalType = ConditionalType.GreaterThan,
                    FieldValue = "0"
                }
                );

            if (!searchModel.queryParams.Code.IsNullOrWhiteSpace())
            {
                param.Add(
                    new ConditionalModel
                    {
                        FieldName = "code",
                        ConditionalType = ConditionalType.Like,
                        FieldValue = searchModel.queryParams.Code
                    }
                );
            }


            if (!searchModel.queryParams.Name.IsNullOrWhiteSpace())
            {
                param.Add(
                    new ConditionalModel
                    {
                        FieldName = "name",
                        ConditionalType = ConditionalType.Like,
                        FieldValue = searchModel.queryParams.Name
                    }
                );
            }

            if (!searchModel.queryParams.MobilePhone.IsNullOrWhiteSpace())
            {
                param.Add(
                    new ConditionalModel
                    {
                        FieldName = "mobile_phone",
                        ConditionalType = ConditionalType.Like,
                        FieldValue = searchModel.queryParams.MobilePhone
                    }
                );
            }

            if (!(searchModel.queryParams.Sex == null))
            {
                param.Add(
                    new ConditionalModel
                    {
                        FieldName = "sex",
                        ConditionalType = ConditionalType.Equal,
                        FieldValue = searchModel.queryParams.Sex.ToString()
                    }
                );
            }

            //配置用户角色 ，登录时已经配置 否则提示重复。
            //db.ConfigQuery.SetTable<SysRole>(it => it.Id, it => it.Name);

            list = db.Queryable<BaUser>().Where(param).Select((u) => new BaUser
            {
                Id = u.Id.SelectAll(),
                RoleName = u.RoleId.GetConfigValue<SysRole>(),
                CreateManName = u.CreateMan.GetConfigValue<BaUser>(),
                ModifyManName = u.ModifyMan.GetConfigValue<BaUser>()
            })
            .ToPageList(searchModel.pageIndex, searchModel.pageSize, ref totalCount);



            PagedList<BaUser> rs = new PagedList<BaUser>();

            rs.Items = list;

            rs.TotalCount = totalCount;

            rs.PageSize = searchModel.pageSize;

            return rs;
        }


        /// <summary>
        /// 新增/修改用户，前端通过formdata提交
        /// var formData = new FormData($("#layui-form")[0]);
        /// </summary>
        /// <param name="files"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        /* 前端提交方式
         * admin.req({
              url: setter.apiUrl + "/user-api/user"
              , type: 'POST'
              , data: formData //JSON.stringify(form.field)
              , processData: false// 不加会报错
              , contentType: false// 服务端formdata方式接收
              // , contentType: "application/json;charset=UTF-8"  //服务端object方式接收
              , success: function(data)
                {
                    if (data.data > 0)
                    {
                        layer.msg('保存成功！');
                    }
                    else layer.msg('保存失败！');
                }
            });
         */
        public int AddUser([FromForm(Name = "files")] List<IFormFile> files, [FromForm] BaUser user)
        {


            #region 文件上传

            #endregion

            int rs = 0;

            if (user.Id == 0)
            {
                //add
                user.Password = StringHelper.GeneratePassword("123456");
                user.CreateMan = user.ModifyMan;
                user.CreateTime = DateTime.Now.ToString();
                //user.Ip = _httpContextAccessor.HttpContext.Request.GetRequestUrlAddress();
                user.LastLoginEnvironment = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].FirstOrDefault().ToString();

                rs = db.Insertable(user).ExecuteCommand();
            }
            else
            {
                //edit
                user.ModifyTime = DateTime.Now.ToString();
                //user.Ip = _httpContextAccessor.HttpContext.Request.GetRequestUrlAddress();
                user.LastLoginEnvironment = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].FirstOrDefault().ToString();
                rs = db.Updateable(user).IgnoreColumns(it => new { it.Password, it.CreateMan, it.CreateTime }).ExecuteCommand();
            }


            return rs;
        }

        /// <summary>
        /// 批量逻辑删除用户
        /// </summary>
        /// <param name="users"></param>
        /// <returns>是否成功</returns>
        public int DeleteUsers(List<BaUser> users)
        {
            int rs = 0;

            if (users.Count == 0) throw Oops.Oh(SystemErrorCodes.E0003);

            users.ForEach(i => i.DeleteFlag = true);

            rs = db.Updateable(users).UpdateColumns(it => new { it.DeleteFlag }).ExecuteCommand();

            return rs;
        }

        /// <summary>
        /// layui.upload, 独立上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost, NonUnify]
        public async Task<int> UploadFileAsync(IFormFile file, [FromForm] BaUser user)
        {
            long size = file.Length;


            if (file.Length > 0)
            {
                var filePath = Path.GetTempFileName();  // 可以替代为你需要存储的真实路径

                using (var stream = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(stream);
                }
            }

            return 0;
        }

    }
}
